Skip to content

Commit

Permalink
Scan String before escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
robb committed Jun 28, 2021
1 parent 209e8a9 commit 7e01603
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 7e01603

Please sign in to comment.