diff --git a/stdlib/public/SDK/Dispatch/Data.swift b/stdlib/public/SDK/Dispatch/Data.swift index 7812896828217..5cea3221fecf4 100644 --- a/stdlib/public/SDK/Dispatch/Data.swift +++ b/stdlib/public/SDK/Dispatch/Data.swift @@ -45,8 +45,9 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. public init(bytes buffer: UnsafeBufferPointer) { - __wrapped = _swift_dispatch_data_create( - buffer.baseAddress!, buffer.count, nil, _swift_dispatch_data_destructor_default()) as! __DispatchData + __wrapped = buffer.baseAddress == nil ? _swift_dispatch_data_empty() + : _swift_dispatch_data_create(buffer.baseAddress!, buffer.count, nil, + _swift_dispatch_data_destructor_default()) as! __DispatchData } /// Initialize a `Data` without copying the bytes. @@ -56,9 +57,8 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// - parameter deallocator: Specifies the mechanism to free the indicated buffer. public init(bytesNoCopy bytes: UnsafeBufferPointer, deallocator: Deallocator = .free) { let (q, b) = deallocator._deallocator - - __wrapped = _swift_dispatch_data_create( - bytes.baseAddress!, bytes.count, q, b) as! __DispatchData + __wrapped = bytes.baseAddress == nil ? _swift_dispatch_data_empty() + : _swift_dispatch_data_create(bytes.baseAddress!, bytes.count, q, b) as! __DispatchData } internal init(data: __DispatchData) { diff --git a/test/stdlib/Dispatch.swift b/test/stdlib/Dispatch.swift index f9dccfc9a7582..5c72cac48f86f 100644 --- a/test/stdlib/Dispatch.swift +++ b/test/stdlib/Dispatch.swift @@ -268,3 +268,25 @@ DispatchAPI.test("DispatchData.copyBytes") { expectEqual(destPtr[5], 0xFF) } +DispatchAPI.test("DispatchData.buffers") { + let bytes = [UInt8(0), UInt8(1), UInt8(2), UInt8(2)] + var ptr = UnsafeBufferPointer(start: bytes, count: bytes.count) + var data = DispatchData(bytes: ptr) + expectEqual(bytes.count, data.count) + for i in 0..(start: nil, count: 0) + data = DispatchData(bytes: ptr) + expectEqual(data.count, 0) + + data = DispatchData(bytesNoCopy: ptr, deallocator: .custom(nil, {})) + expectEqual(data.count, 0) +}