File tree 2 files changed +28
-10
lines changed
Darwin/Foundation-swiftoverlay
2 files changed +28
-10
lines changed Original file line number Diff line number Diff line change @@ -208,14 +208,23 @@ extension String {
208
208
/// - encoding: The encoding to use to interpret `bytes`.
209
209
public init ? < S: Sequence > ( bytes: __shared S, encoding: Encoding )
210
210
where S. Iterator. Element == UInt8 {
211
- let byteArray = Array ( bytes)
212
- if encoding == . utf8,
213
- let str = byteArray. withUnsafeBufferPointer ( { String . _tryFromUTF8 ( $0) } )
214
- {
215
- self = str
211
+ if encoding == . utf8 {
212
+ if let str = bytes. withContiguousStorageIfAvailable ( { String . _tryFromUTF8 ( $0) } ) {
213
+ guard let str else {
214
+ return nil
215
+ }
216
+ self = str
217
+ } else {
218
+ let byteArray = Array ( bytes)
219
+ guard let str = byteArray. withUnsafeBufferPointer ( { String . _tryFromUTF8 ( $0) } ) else {
220
+ return nil
221
+ }
222
+ self = str
223
+ }
216
224
return
217
225
}
218
226
227
+ let byteArray = Array ( bytes)
219
228
if let ns = NSString (
220
229
bytes: byteArray, length: byteArray. count, encoding: encoding. rawValue) {
221
230
self = String . _unconditionallyBridgeFromObjectiveC ( ns)
Original file line number Diff line number Diff line change @@ -256,14 +256,23 @@ extension String {
256
256
/// - encoding: The encoding to use to interpret `bytes`.
257
257
public init ? < S: Sequence > ( bytes: __shared S, encoding: Encoding )
258
258
where S. Iterator. Element == UInt8 {
259
- let byteArray = Array ( bytes)
260
- if encoding == . utf8,
261
- let str = byteArray. withUnsafeBufferPointer ( { String . _tryFromUTF8 ( $0) } )
262
- {
263
- self = str
259
+ if encoding == . utf8 {
260
+ if let str = bytes. withContiguousStorageIfAvailable ( { String . _tryFromUTF8 ( $0) } ) {
261
+ guard let str else {
262
+ return nil
263
+ }
264
+ self = str
265
+ } else {
266
+ let byteArray = Array ( bytes)
267
+ guard let str = byteArray. withUnsafeBufferPointer ( { String . _tryFromUTF8 ( $0) } ) else {
268
+ return nil
269
+ }
270
+ self = str
271
+ }
264
272
return
265
273
}
266
274
275
+ let byteArray = Array ( bytes)
267
276
if let ns = NSString (
268
277
bytes: byteArray, length: byteArray. count, encoding: encoding. rawValue) {
269
278
self = String . _unconditionallyBridgeFromObjectiveC ( ns)
You can’t perform that action at this time.
0 commit comments