diff --git a/Sources/Swim/String+XML.swift b/Sources/Swim/String+XML.swift index fcd4d80..dc28a6b 100644 --- a/Sources/Swim/String+XML.swift +++ b/Sources/Swim/String+XML.swift @@ -2,14 +2,29 @@ import Foundation extension String { func addingXMLEncoding() -> String { + guard unicodeScalars.contains(where: \.needsEscaping) else { + return self + } + var result = "" result.reserveCapacity(count) - return unicodeScalars.reduce(into: result, { $0.append($1.named_escapingIfNeeded) }) + return unicodeScalars.reduce(into: result, { $0.append($1.escapingIfNeeded) }) } } extension UnicodeScalar { - fileprivate var named_escapingIfNeeded: String { + fileprivate var needsEscaping: Bool { + switch value { + case ("&" as Unicode.Scalar).value, ("<" as Unicode.Scalar).value, + (">" as Unicode.Scalar).value, ("\'" as Unicode.Scalar).value, + ("\"" as Unicode.Scalar).value: + return true + default: + return false + } + } + + fileprivate var escapingIfNeeded: String { switch value { case ("&" as Unicode.Scalar).value: return "&"