Skip to content

Instantly share code, notes, and snippets.

@zwaldowski
Last active September 3, 2018 08:32
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zwaldowski/bd33c286c5a75eebc8763bca6f0043ed to your computer and use it in GitHub Desktop.
import Foundation
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension Data {
init(referencing data: DispatchData) {
self = (data as AnyObject) as! Data
}
}
extension DispatchData {
init(referencing data: Data) {
guard !data.isEmpty else {
self = .empty
return
}
// will perform a copy if needed
let nsData = data as NSData
if let dispatchData = ((nsData as AnyObject) as? DispatchData) {
self = dispatchData
} else {
self = .empty
nsData.enumerateBytes { (bytes, byteRange, _) in
let innerData = Unmanaged.passRetained(nsData)
let buffer = UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: byteRange.length)
let chunk = DispatchData(bytesNoCopy: buffer, deallocator: .custom(nil, innerData.release))
append(chunk)
}
}
}
}
#endif
let nsData1 = "Hello, ".data(using: .utf8)! // => 7 bytes
let nsData2 = "world!".data(using: .utf8)! // => 6 bytes
var dData = DispatchData(referencing: nsData1) // => DispatchData
let dData2 = DispatchData(referencing: nsData2) // => DispatchData
dData.append(dData2)
dData.count // => 13
var numberOfChunks = 0
dData.enumerateBytes { _ in numberOfChunks += 1 }
numberOfChunks // => 2
let combinedNsData = Data(referencing: dData) // => 13 bytes
type(of: combinedNsData as NSData) // OS_dispatch_data.Type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment