Skip to content

Commit f14cf81

Browse files
use DispatchData(bytesNoCopy:deallocator:) with custom deallocator
1 parent 0c49fb1 commit f14cf81

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Foundation/URLSession/BodySource.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,23 @@ extension _BodyStreamSource : _BodySource {
7272
}
7373

7474
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: length, alignment: MemoryLayout<UInt8>.alignment)
75-
defer { buffer.deallocate() }
7675

7776
guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
77+
buffer.deallocate()
7878
return .error
7979
}
8080

8181
let readBytes = self.inputStream.read(pointer, maxLength: length)
8282
if readBytes > 0 {
83-
let dispatchData = DispatchData(bytes: UnsafeRawBufferPointer(buffer))
83+
let dispatchData = DispatchData(bytesNoCopy: UnsafeRawBufferPointer(buffer), deallocator: .custom(nil, { buffer.deallocate() }))
8484
return .data(dispatchData.subdata(in: 0 ..< readBytes))
8585
}
8686
else if readBytes == 0 {
87+
buffer.deallocate()
8788
return .done
8889
}
8990
else {
91+
buffer.deallocate()
9092
return .error
9193
}
9294
}

0 commit comments

Comments
 (0)