Skip to content

Commit

Permalink
Merge pull request #30 from robb/scan-first
Browse files Browse the repository at this point in the history
Scan String before escaping
  • Loading branch information
robb authored Jun 28, 2021
2 parents 209e8a9 + 7e01603 commit 58bf32d
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions Sources/Swim/String+XML.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 "&amp;"
Expand Down

0 comments on commit 58bf32d

Please sign in to comment.