|
1 | 1 | extension String { |
2 | 2 | init(cString: UnsafePointer<CChar>, withLength length: Int) { |
3 | | -// self = String.decodeCString(UnsafePointer(cString), withLength: length, as: UTF8.self, repairingInvalidCodeUnits: true)!.result |
4 | | - self = cString.withMemoryRebound(to: UInt8.self, capacity: length) { |
5 | | - String._fromCodeUnitSequenceWithRepair(UTF8.self, input: UnsafeBufferPointer(start: $0, count: length)).0 |
6 | | - } |
| 3 | + let utf8buffer = UnsafeBufferPointer(start: UnsafeRawPointer(cString).assumingMemoryBound(to: UInt8.self), count: length) |
| 4 | + self = String(decoding: utf8buffer, as: UTF8.self) |
7 | 5 | } |
8 | 6 |
|
9 | | -/* @_specialize(UTF8) |
10 | | - @warn_unused_result |
11 | | - static func decodeCString<Encoding: UnicodeCodec>( |
12 | | - _ cString: UnsafePointer<Encoding.CodeUnit>?, withLength length: Int, |
13 | | - as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true) |
14 | | - -> (result: String, repairsMode: Bool)? { |
15 | | - |
16 | | - guard let cString = cString else { return nil } |
17 | | - let buffer = UnsafeBufferPointer<Encoding.CodeUnit>(start: cString, count: length) |
18 | | - |
19 | | - var string = String() |
20 | | - var enc = Encoding.init() |
21 | | - var iter = buffer.makeIterator() |
22 | | - var hadError = false |
23 | | - while true { |
24 | | - let res = enc.decode(&iter) |
25 | | - switch res { |
26 | | - case .scalarValue(let us): |
27 | | - string.append(us) |
28 | | - case .emptyInput: |
29 | | - return (result: string, repairsMode: hadError) |
30 | | - case .error: |
31 | | - string.append(UnicodeScalar(0xfffd)) |
32 | | - hadError = true |
33 | | - } |
34 | | - } |
35 | | - }*/ |
36 | | - |
37 | 7 | func withCStringWithLength<Result>(_ body: (UnsafePointer<CChar>, Int) throws -> Result) rethrows -> Result { |
38 | | - let array = ContiguousArray<UTF8.CodeUnit>(self.utf8) |
39 | | - return try array.withUnsafeBufferPointer { buf in |
40 | | - try buf.baseAddress!.withMemoryRebound(to: CChar.self, capacity: buf.count) { |
41 | | - try body($0, buf.count) |
42 | | - } |
43 | | - } |
| 8 | + let length = utf8.count |
| 9 | + return try withCString { try body($0, length) } |
44 | 10 | } |
45 | 11 | } |
0 commit comments