When working with small files, the compression may fail and compression_encode_buffer(_:_:_:_:_:_:) returns 0:
You may elect to handle this situation differently, for example, by displaying a warning to the user that the compression failed.
Write the Encoded Data to a File
The following code writes the encoded data to a file in the the app's temporary directory on macOS:
Read the Encoded Data from a File
To read the encoded file, create a file handle for reading for the encoded file's URL:
Use the file handle to read the entire encoded data and populate encodedSourceData:
Decompress the Data
Allocate memory to contain the decoded data. Typically, the encoded payload would be part of a larger structure containing additional metadata such as the uncompressed size, and you'd use that to define the buffer capacity. However, for this example, allocate 8 MB:
The compression_decode_buffer(_:_:_:_:_:_:) function returns the size of the decoded data. If the decompression fails, the size returned is zero. This may indicate that the memory allocated to the destination buffer is insufficient and you should switch to the stream API or retry with a larger buffer.