Last active
June 16, 2021 23:07
-
-
Save mayoff/6e35e263b9ddd04d9b77e5261212be19 to your computer and use it in GitHub Desktop.
How to convert from DispatchData to Data without copying the bytes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
UPDATE! It turns out this is the most efficient way to convert a
DispatchData
to aData
, both in source code size and in memory and CPU time: