From 7e01603a9b4a21cd5176b6a4bb60ccdd70f88352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robert=20B=C3=B6hnke?= Date: Mon, 28 Jun 2021 12:39:03 +0200 Subject: [PATCH] Scan String before escaping --- Sources/Swim/String+XML.swift | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) 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 "&"