Skip to content

Instantly share code, notes, and snippets.

@mayoff
Last active June 16, 2021 23:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayoff/6e35e263b9ddd04d9b77e5261212be19 to your computer and use it in GitHub Desktop.
Save mayoff/6e35e263b9ddd04d9b77e5261212be19 to your computer and use it in GitHub Desktop.
How to convert from DispatchData to Data without copying the bytes
import Dispatch
import Foundation
var x = 7
let dd = withUnsafeBytes(of: &x, { DispatchData.init(bytes: $0) })
print(dd as? Data) // Case 1: nil
print(dd as? NSData) // Case 2: nil
print(dd as Any as? Data) // Case 3: nil
print(dd as Any as? NSData) // Case 4: .some
print(dd as Any as? NSData as Data?) // Case 5: .some
let d = dd as Any as! NSData as Data
print(dd.withUnsafeBytes(body: { Int(bitPattern: $0) }) == d.withUnsafeBytes({ Int(bitPattern: $0) }))
// true
@mayoff
Copy link
Author

mayoff commented Jun 8, 2018

UPDATE! It turns out this is the most efficient way to convert a DispatchData to a Data, both in source code size and in memory and CPU time:

let d = dd as AnyObject as! Data

@MychiloCline
Copy link

MychiloCline commented Jun 16, 2021

That did the trick!

let decompressedData = try (data as NSData).decompressed(using: compressionAlgorithm)
let payload = Data(compressedData)

Compiles fine, but crashes when it tries to access compressedData. But if cast it - following Mayoff's recommendation - we are in business.

guard let decompressedData = try (data as NSData).decompressed(using: compressionAlgorithm) as AnyObject as? Data else { }
let output = try JSONDecoder().decode(outputDataType, from: decompressedData)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment