@@ -29,6 +29,9 @@ class TestNSString : XCTestCase {
2929 ( " test_FromASCIINSData " , test_FromASCIINSData ) ,
3030 ( " test_FromUTF8NSData " , test_FromUTF8NSData ) ,
3131 ( " test_FromMalformedUTF8NSData " , test_FromMalformedUTF8NSData ) ,
32+ ( " test_FromNullTerminatedCStringInASCII " , test_FromNullTerminatedCStringInASCII ) ,
33+ ( " test_FromNullTerminatedCStringInUTF8 " , test_FromNullTerminatedCStringInUTF8 ) ,
34+ ( " test_FromMalformedNullTerminatedCStringInUTF8 " , test_FromMalformedNullTerminatedCStringInUTF8 ) ,
3235 ]
3336 }
3437
@@ -97,4 +100,24 @@ class TestNSString : XCTestCase {
97100 let string = NSString ( data: data, encoding: NSUTF8StringEncoding)
98101 XCTAssertNil ( string)
99102 }
103+
104+ func test_FromNullTerminatedCStringInASCII( ) {
105+ let bytes : [ UInt8 ] = [ 0x48 , 0x65 , 0x6C , 0x6C , 0x6F , 0x20 , 0x53 , 0x77 , 0x69 , 0x66 , 0x74 , 0x21 , 0x00 ] // "Hello Swift!"
106+ let string = NSString ( CString: bytes. map { Int8 ( bitPattern: $0) } , encoding: NSASCIIStringEncoding)
107+ XCTAssertNotNil ( string)
108+ XCTAssertTrue ( string!. isEqualToString ( " Hello Swift! " ) )
109+ }
110+
111+ func test_FromNullTerminatedCStringInUTF8( ) {
112+ let bytes : [ UInt8 ] = [ 0x49 , 0x20 , 0xE2 , 0x9D , 0xA4 , 0xEF , 0xB8 , 0x8F , 0x20 , 0x53 , 0x77 , 0x69 , 0x66 , 0x74 ] // "I ❤️ Swift"
113+ let string = NSString ( CString: bytes. map { Int8 ( bitPattern: $0) } , encoding: NSUTF8StringEncoding)
114+ XCTAssertNotNil ( string)
115+ XCTAssertTrue ( string? . isEqualToString ( " I ❤️ Swift " ) ?? false )
116+ }
117+
118+ func test_FromMalformedNullTerminatedCStringInUTF8( ) {
119+ let bytes : [ UInt8 ] = [ 0xFF , 0x00 ]
120+ let string = NSString ( CString: bytes. map { Int8 ( bitPattern: $0) } , encoding: NSUTF8StringEncoding)
121+ XCTAssertNil ( string)
122+ }
100123}
0 commit comments