File tree Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Original file line number Diff line number Diff line change @@ -73,4 +73,20 @@ public extension String {
73
73
public mutating func shellEscape( ) {
74
74
self = shellEscaped ( )
75
75
}
76
+
77
+ /// Prepends every acsii scalar in the string with escape character '\', if present.
78
+ public func escape( ascii: UnicodeScalar ) -> String {
79
+ guard let pos = utf8. index ( where: { $0 == UInt8 ( ascii: ascii) } ) else {
80
+ return self
81
+ }
82
+ var newString = String ( utf8 [ utf8. startIndex..< pos] ) !
83
+ for char in utf8 [ pos..< utf8. endIndex] {
84
+ if char == UInt8 ( ascii: ascii) {
85
+ newString += " \\ " + String( UnicodeScalar ( ascii) )
86
+ } else {
87
+ newString += String ( UnicodeScalar ( char) )
88
+ }
89
+ }
90
+ return newString
91
+ }
76
92
}
Original file line number Diff line number Diff line change @@ -37,6 +37,13 @@ class StringConversionTests: XCTestCase {
37
37
str = " hello \n A \" B C>D*[$;()^>< "
38
38
XCTAssertEqual ( " 'hello \n A \" B C>D*[$;()^><' " , str. shellEscaped ( ) )
39
39
}
40
+
41
+ func testEscapeAscii( ) {
42
+ XCTAssertEqual ( " hello " , " hello " . escape ( ascii: " " ) )
43
+ XCTAssertEqual ( " \\ hello " , " hello " . escape ( ascii: " h " ) )
44
+ XCTAssertEqual ( " hi \\ hello " , " hi hello " . escape ( ascii: " " ) )
45
+ XCTAssertEqual ( " hel \\ \\ lo " , " hel \\ lo " . escape ( ascii: " " ) )
46
+ }
40
47
41
48
static var allTests = [
42
49
( " testShellEscaped " , testShellEscaped) ,
You can’t perform that action at this time.
0 commit comments