// Copied from Equipo's EquipoKit (oficina/equipo 00d09aa7, // native/apple/Sources/EquipoKit/Markdown/MarkdownEntities.swift). Base's changes are // marked "Base:"; keep the rest in step with Equipo's. import Foundation import cmark_gfm /// The web has distinct text and destination decoders. Text uses Goldmark's /// numeric pass followed by its name pass; destinations decode proper HTML /// entities once. Keeping these separate preserves nested escapes and queries. enum MarkdownEntities { private enum Mode { case link, numericText, namedText } static func link(_ value: String) -> String { decode(value, mode: .link) } static func text(_ value: String) -> String { decode(decode(value, mode: .numericText), mode: .namedText) } private static func alphaNumeric(_ b: UInt8) -> Bool { (48...57).contains(b) || (65...90).contains(b) || (97...122).contains(b) } private static func decode(_ value: String, mode: Mode) -> String { let bytes = Array(value.utf8) var out: [UInt8] = [], at = 0 while at < bytes.count { guard bytes[at] == 38 else { out.append(bytes[at]); at += 1; continue } let begin = at var end = at + 1 let numeric = end < bytes.count && bytes[end] == 35 if numeric { end += 1 } while end < bytes.count, alphaNumeric(bytes[end]) { end += 1 } guard end < bytes.count, bytes[end] == 59, end > at + (numeric ? 2 : 1) else { out.append(bytes[at]); at += 1; continue } let entity = String(decoding: bytes[begin...end], as: UTF8.self) var replacement: String? if numeric, mode != .namedText { var digits = Array(bytes[(begin + 2).. String? { if text, !hex, digits.count >= 8 { return nil } // Goldmark's decimal text pass uses ParseUint(base: 0), so a leading // zero selects octal. Its hexadecimal pass accepts any digit count. let radix: UInt32 = hex ? 16 : text && digits.first == 48 ? 8 : 10 var value: UInt32 = 0 for byte in digits { let digit = UInt32(byte <= 57 ? byte - 48 : (byte | 32) - 87) if text { if digit >= radix { value = 0; break } let multiplied = value.multipliedReportingOverflow(by: radix) let added = multiplied.partialValue.addingReportingOverflow(digit) if multiplied.overflow || added.overflow { value = .max; break } value = added.partialValue } else { // html.UnescapeString accumulates a signed 32-bit rune. value = value &* radix &+ digit } } if !text, (0x80...0x9f).contains(value) { let windows: [UInt32] = [0x20ac,0x81,0x201a,0x192,0x201e,0x2026,0x2020,0x2021,0x2c6,0x2030,0x160,0x2039,0x152,0x8d,0x17d,0x8f,0x90,0x2018,0x2019,0x201c,0x201d,0x2022,0x2013,0x2014,0x2dc,0x2122,0x161,0x203a,0x153,0x9d,0x17e,0x178] value = windows[Int(value - 0x80)] } guard value != 0, let scalar = Unicode.Scalar(value) else { return "\u{fffd}" } return String(scalar) } }