Created
April 8, 2024 16:53
-
-
Save Brandon7CC/7f555bfc75bd1281750a9f3224133117 to your computer and use it in GitHub Desktop.
Compress a string with LZFSE
This file contains 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 Foundation | |
import Compression | |
import OSLog | |
// Compress JSON representation with the Apple recommended compression algo LZFSE | |
// https://developer.apple.com/documentation/compression/algorithm/lzfse | |
public func getCompressedJSON(from jsonString: String) -> Data { | |
var sourceBuffer = Array(jsonString.utf8) | |
let destinationBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: jsonString.count) | |
let algorithm = COMPRESSION_LZFSE | |
let compressedSize = compression_encode_buffer(destinationBuffer, jsonString.count, | |
&sourceBuffer, jsonString.count, | |
nil, | |
algorithm) | |
if compressedSize == 0 { | |
os_log("Encoding failed.") | |
} | |
return NSData(bytesNoCopy: destinationBuffer, length: compressedSize) as Data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment