@@ -35,6 +35,54 @@ import AppKit
3535import UIKit
3636#endif
3737
38+ extension String {
39+
40+ // Current implementation by @alexaubry in
41+ // https://github.com/alexaubry/HTMLString
42+ public func escapeWithUnicodeEntities( ) -> String {
43+ var copy = self
44+ copy. addUnicodeEntities ( )
45+ return copy
46+ }
47+
48+ internal mutating func addUnicodeEntities( ) {
49+ var position : String . Index ? = startIndex
50+ let requiredEscapes : Set < Character > = [ " ! " , " \" " , " $ " , " % " , " & " , " ' " , " + " , " , " , " < " , " = " , " > " , " @ " , " [ " , " ] " , " ` " , " { " , " } " ]
51+
52+ while let cursorPosition = position {
53+ guard cursorPosition != endIndex else { break }
54+ let character = self [ cursorPosition]
55+
56+ if requiredEscapes. contains ( character) {
57+ // One of the required escapes for security reasons
58+ let escape = " &# \( character. asciiValue!) ; " // required escapes can can only be ASCII
59+ position = positionAfterReplacingCharacter ( at: cursorPosition, with: escape)
60+ } else {
61+ // Not a required escape, no need to replace the character
62+ position = index ( cursorPosition, offsetBy: 1 , limitedBy: endIndex)
63+ }
64+ }
65+ }
66+
67+ /// Replaces the character at the given position with the escape and returns the new position.
68+ fileprivate mutating func positionAfterReplacingCharacter( at position: String . Index , with escape: String ) -> String . Index ? {
69+ let nextIndex = index ( position, offsetBy: 1 )
70+
71+ if let fittingPosition = index ( position, offsetBy: escape. count, limitedBy: endIndex) {
72+ // Check if we can fit the whole escape in the receiver
73+ replaceSubrange ( position ..< nextIndex, with: escape)
74+ return fittingPosition
75+ } else {
76+ // If we can't, remove the character and insert the escape to make it fit.
77+ remove ( at: position)
78+ insert ( contentsOf: escape, at: position)
79+ return index ( position, offsetBy: escape. count, limitedBy: endIndex)
80+ }
81+ }
82+
83+
84+ }
85+
3886extension NSNumber {
3987
4088 internal static func from( float: Float ? ) -> NSNumber ? {
0 commit comments