Skip to content

Instantly share code, notes, and snippets.

@Brandon7CC
Created April 8, 2024 16:53
Show Gist options
  • Save Brandon7CC/7f555bfc75bd1281750a9f3224133117 to your computer and use it in GitHub Desktop.
Save Brandon7CC/7f555bfc75bd1281750a9f3224133117 to your computer and use it in GitHub Desktop.
Compress a string with LZFSE
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