Skip to content

Commit edfa624

Browse files
committed
[Basic] Add string extension to escape any unicode scalar
1 parent e7aa948 commit edfa624

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Sources/Basic/StringConversions.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,20 @@ public extension String {
7373
public mutating func shellEscape() {
7474
self = shellEscaped()
7575
}
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+
}
7692
}

Tests/BasicTests/StringConversionsTests.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ class StringConversionTests: XCTestCase {
3737
str = "hello\nA\"B C>D*[$;()^><"
3838
XCTAssertEqual("'hello\nA\"B C>D*[$;()^><'", str.shellEscaped())
3939
}
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+
}
4047

4148
static var allTests = [
4249
("testShellEscaped", testShellEscaped),

0 commit comments

Comments
 (0)